package top.moonkit.rs_pro.utils;

import cn.hutool.core.util.IdUtil;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.moonkit.rs_pro.common.Result;
import top.moonkit.rs_pro.entity.UserToken;
import top.moonkit.rs_pro.exception.LoginException;
import top.moonkit.rs_pro.service.UserTokenService;

import java.sql.Timestamp;
import java.time.LocalDateTime;

import static top.moonkit.rs_pro.entity.table.UserTokenTableDef.USER_TOKEN;

/**
 * AuthUtil
 * 获取用户授权相关信息
 *
 * @author moon
 * @since 0.0.1
 */
@Component
public class Au {

    private static HttpServletRequest request;

    private static  UserTokenService tokenService;

    @Autowired
    public void setRequest(HttpServletRequest request) {
        Au.request = request;
    }

    @Autowired
    public void setTokenService(UserTokenService tokenService) {
        Au.tokenService = tokenService;
    }
    public static String getToken(){
        return request.getHeader("Authorization");
    }

    public static UserToken checkAndGetToken(){
        String token = getToken();
        if(token == null){
            throw new LoginException(Mu.m("login.exception"));
        }
        UserToken userToken = tokenService.getOne(
                QueryWrapper.create()
                        .and(USER_TOKEN.TOKEN.eq(token))
                        .and(USER_TOKEN.EXPIRE_TIME.gt(Timestamp.valueOf(LocalDateTime.now())))
        );
        if (userToken == null){
            throw new LoginException(Mu.m("login.exception"),Mu.m("login.expire"));
        }
        return userToken;
    }

    /**
     * 移出token
     */
    public static void removeToken(){
        tokenService.remove(
                QueryWrapper.create()
                        .and(USER_TOKEN.TOKEN.eq(getToken()))
        );
    }
    /**
     * 创建token并返回
     */
    public static String createToken(Long userId, Boolean rememberMe) {
        String token = IdUtil.simpleUUID();
        UserToken userToken = new UserToken();
        userToken.setUserId(userId);
        userToken.setToken(token);
        userToken.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        userToken.setExpireTime(rememberMe != null && rememberMe ? Timestamp.valueOf(LocalDateTime.now().plusDays(300)) : Timestamp.valueOf(LocalDateTime.now().plusHours(8)));
        tokenService.save(userToken);
        return token;
    }



}
